package com.txm.qqserver.service;

import com.txm.qqcommon.Message;
import com.txm.qqcommon.MessageType;
import com.txm.qqcommon.User;

import java.io.ObjectOutputStream;

/**
检测发送人是否在线，当用户在线时，将留言发送给用户
*/
public class LeaveMessage extends Thread {
    Message msg = null;

    Message toClient = null;


    public LeaveMessage() {
    }

    public LeaveMessage(Message msg, ServerConnectServerThread backScst) {
        try {
            this.setName(msg.getGetter() + Message.getLocalDate());
            this.msg = msg;
            toClient = new Message();
            toClient.setCurrentLocalDate();
            toClient.setMsgType(MessageType.MESSAGE_CHAT_USER);
            toClient.setObject(msg.getObject());

            ObjectOutputStream backSender = new ObjectOutputStream(backScst.accept.getOutputStream());
            toClient.setContent("我 -> " + msg.getGetter() + ":" + msg.getContent());
            backSender.writeObject(toClient);

            toClient.setContent(msg.getSender() + ":" + msg.getContent());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                User user = (User) msg.getObject();
                ServerConnectServerThread thread = (ServerConnectServerThread) ManageClientThreads.getMcts().get(user.getUserId());
                System.out.println(this.getName() + "检测" + user.getUsername() + "是否上线。");
                if (thread == null) continue;
                ObjectOutputStream toGetter = new ObjectOutputStream(thread.accept.getOutputStream());
//                System.out.println("LeaveMessage run:" + toClient);
                toGetter.writeObject(toClient);
                System.out.println(this.getName() + "消息已发送，退出。");
                break;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
